package net.dipper.tankwar.editor.ui;

import java.awt.Dimension;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.filechooser.FileNameExtensionFilter;

import net.dipper.tankwar.core.data.ObjectMap;
import net.dipper.tankwar.core.helper.GameFileManager;
import net.dipper.tankwar.core.helper.Position;
import net.dipper.tankwar.core.helper.ViewPort;

public class OperationPane extends JPanel implements ActionListener {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private JButton btnLoad;
	private JButton btnSave;
	private JButton btnSelect;
	private JButton btnDelete;
	private JButton btnSetPlayer;
	private MiniMap miniMap;
	private EditorContext context;
	
	public OperationPane(EditorContext context){
		this.context = context;
		
		this.btnLoad = new JButton("打开游戏文件");
		this.btnSave = new JButton("保存游戏");
		this.btnSelect = new JButton("选择对象");
		this.btnDelete = new JButton("删除对象");
		this.btnSetPlayer = new JButton("设为玩家");
		this.miniMap = new MiniMap(this.context, 200, true);
		
		this.btnLoad.setMaximumSize(new Dimension(150, 24));
		this.btnSave.setMaximumSize(new Dimension(150, 24));
		this.btnSelect.setMaximumSize(new Dimension(150, 24));
		this.btnDelete.setMaximumSize(new Dimension(150, 24));
		this.btnSetPlayer.setMaximumSize(new Dimension(150, 24));
		
		this.btnLoad.addActionListener(this);
		this.btnSave.addActionListener(this);
		this.btnSelect.addActionListener(this);
		this.btnDelete.addActionListener(this);
		this.btnSetPlayer.addActionListener(this);
		this.miniMap.setSize(new Dimension(150, 150));
		
		
		setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
		add(Box.createRigidArea(new Dimension(10, 10)));
		add(btnLoad);
		add(Box.createRigidArea(new Dimension(10, 10)));
		add(btnSave);
		add(Box.createRigidArea(new Dimension(10, 10)));
		add(btnSelect);
		add(Box.createRigidArea(new Dimension(10, 10)));
		add(btnDelete);
		add(Box.createRigidArea(new Dimension(10, 10)));
		add(btnSetPlayer);
		add(Box.createVerticalGlue());
		add(miniMap);
		
		setSize(new Dimension(160, 600));
		
		miniMap.start();
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		Point p = context.getSelected();
		ObjectMap map = context.getMap();
		ViewPort v = context.getViewPort();
		Object source = e.getSource();
		
		if(source.equals(btnSelect)){
			context.setMode(EditorContext.MODE_DISPLAY);
		}else if(source.equals(btnDelete)){
			Position position = map.getPlayer();
			if(position.x == p.x + v.x && position.y == p.y + v.y){
				map.setPlayer(-1, -1);
			}
			
			map.setObject(p.x + v.x, p.y + v.y, (byte)0);
			map.setHealth(p.x + v.x, p.y + v.y, 0);
			context.setIsDirty(true);
		}else if(source.equals(btnSetPlayer)){
			byte value = map.getObject(p.x + v.x, p.y + v.y);
			if(value != 0){
				map.setPlayer(p.x + v.x, p.y + v.y);
				context.setIsDirty(true);
			}
		}else if(source.equals(btnSave)){
			saveGame(context.getMap());
		}else if(source.equals(btnLoad)){
			loadGame();
		}
	}
	
	private void loadGame() {
		boolean saveResult = true;
		if(context.getIsDirty()){
			int result = JOptionPane.showConfirmDialog(this, "文件尚未保存，是否先保存文件？");
			if(result == JOptionPane.OK_OPTION){
				saveResult = saveGame(context.getMap());
			}
		}
		
		if(saveResult){
			try{
				File file = getFileToLoad();
				if(file == null)
					return;
				else if(!file.exists() || !file.canRead()){
					JOptionPane.showMessageDialog(this, "文件不存在或不可读");
				}else{
					ObjectMap map = GameFileManager.load(new FileInputStream(file));
					context.setMap(map);
				}
			}catch(FileNotFoundException ex){
				JOptionPane.showMessageDialog(this, "无法打开文件");
			} catch (IOException e) {
				JOptionPane.showMessageDialog(this, "对不起，打开文件失败");
			}
		}
	}

	private File getFileToLoad() {
		JFileChooser chooser = new JFileChooser();
		FileNameExtensionFilter filter = new FileNameExtensionFilter("坦克大战游戏文件", GameFileManager.EXT);
		chooser.setFileFilter(filter);
		int result = chooser.showOpenDialog(this);
		if(result == JFileChooser.APPROVE_OPTION){
			return chooser.getSelectedFile();
		}
		
		return null;
	}

	private boolean saveGame(ObjectMap map){
		Position player = map.getPlayer();
		if(player.x < 0 || player.y < 0){
			JOptionPane.showMessageDialog(this, "您尚未设置玩家位置，请设置之后再保存");
			return false;
		}
		
		File file = getFileToSave();
		if(file == null)
			return false;
	
		try {
			if(!file.exists()){
				file.createNewFile();
			}
			
			GameFileManager.save(context.getMap(), new FileOutputStream(file));			
			context.setIsDirty(false);
			return true;
		} catch (IOException ex) {
			JOptionPane.showMessageDialog(this, "保存文件失败，请检查是否有相关读写权限");
		}
		
		return false;
	}

	private File getFileToSave() {
		JFileChooser chooser = new JFileChooser();
		FileNameExtensionFilter filter = new FileNameExtensionFilter("坦克大战游戏文件", GameFileManager.EXT);
		chooser.setFileFilter(filter);
		chooser.setMultiSelectionEnabled(false);
		int result = chooser.showSaveDialog(this);
		if(result == JFileChooser.APPROVE_OPTION){
			return chooser.getSelectedFile();
		}
		
		return null;
	}
}
